﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AidBrella.BLL;
using AidBrella.ViewModels;
using AidBrella.Enums;

namespace AidBrella.Controllers
{
    [Authorize]
    public class ProjectController : Controller
    {
        private readonly ProjectModel _model = new ProjectModel();
        private readonly ProjectViewModelService _service = new ProjectViewModelService();
        private readonly UserModel _userModel = new UserModel();
        // GET: /Project/
     
        public ActionResult Index()
        {
            var service = new ProjectViewModelService();
            var projects = new List<ProjectViewModel>();
            var userId = _userModel.GetUserId(HttpContext.User.Identity.Name);
            var items = service.GetProjects(userId);
            foreach (var item in items)
            {
                item.UserId = _userModel.GetUserId(HttpContext.User.Identity.Name);
                projects.Add(item);
            }

            return View(projects);
        }

        public ActionResult View(int id)
        {
            var userId = _userModel.GetUserId(HttpContext.User.Identity.Name);
            var project = _service.GetProject(id, userId);
            return View(project);
        }

       

        //
        // GET: /Project/Create

        public ActionResult Create()
        {
            var vm = new ProjectViewModel
                         {
                             ProjectSectorSelection = _service.GetProjectSectorSelectionList()
                         };
            return View(vm);
        } 

        //
        // POST: /Project/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            
            try
            {
                string location = collection["Location"];
                string[] longlat = location.Split(',');
                string lat = string.Empty;
                string lon = string.Empty;

                var loccc = new LocationViewModel();

                if (longlat.Length == 2)
                {
                    lat = longlat[0].Replace("[Location ", "");
                    lon = longlat[1].Replace("]", "");
#if DEBUG
                    lat = lat.Replace(".", ",");
                    lon = lon.Replace(".", ",");
 #endif   
                    loccc.Latitude = Double.Parse(lat);
                    loccc.Longitude = Double.Parse(lon);
               }
                else
                {
                    loccc.Latitude = Convert.ToDouble("60.180821883782514");
                    loccc.Longitude = Convert.ToDouble("24.831746792793446");
                }

                string[] startDate = collection["StartDate"].Split('/');
                string[] endDate = collection["EndDate"].Split('/');
                
                     var v = new ProjectViewModel
                            {
                                Name = collection["Name"],
                                Description = collection["Description"],
                                ProjectSectorId = Convert.ToInt32(collection["ProjectSectorSelection"]),
                                SelectedCountry = collection["country-list"],
                                ProjectSectorSelection = _service.GetProjectSectorSelectionList(),
                                Location = loccc,
                                UserName = this.User.Identity.Name,
                                UserId = _userModel.GetUserId(this.User.Identity.Name),
                                StartDate = new DateTime(Convert.ToInt16(startDate[2]), Convert.ToInt16(startDate[0]), Convert.ToInt16(startDate[1])),
                                EndDate = new DateTime(Convert.ToInt16(endDate[2]), Convert.ToInt16(endDate[0]), Convert.ToInt16(endDate[1]))
                            };

                _service.CreateProject(v);
                return RedirectToAction("Index");
            }
            catch
            {
                var v = new ProjectViewModel { ProjectSectorSelection = _service.GetProjectSectorSelectionList() };
                return View(v);
            }
            
        }
        
        //
        // GET: /Project/Edit/5
 
        public ActionResult Edit(int id)
        {
            var vm = _service.GetProject(id);
            vm.ProjectSectorSelection = _service.GetProjectSectorSelectionList(vm.ProjectSectorId,true);

            return View(vm);
        }

        //
        // POST: /Project/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                string name = collection["Name"];
                int projectSector = Convert.ToInt32( collection["ProjectSectorSelection"]);
                string desc = collection["txtDesc"];

                string[] startDate = collection["StartDate"].Split('/');
                string[] endDate = collection["EndDate"].Split('/');


                ProjectViewModel pr = _service.GetProject(id);
                pr.Name = name;
                pr.ProjectSectorId = projectSector;
                pr.Description = desc;
                pr.ProjectSectorSelection = _service.GetProjectSectorSelectionList();
                if (startDate.Length == 1 && endDate.Length == 1)
                {
                    pr.StartDate = Convert.ToDateTime(startDate[0]);
                    pr.EndDate = Convert.ToDateTime(endDate[0]);
                }
                else if (startDate.Length == 3 && endDate.Length == 3)
                {
                     pr.StartDate =  new DateTime(Convert.ToInt16(startDate[2]), Convert.ToInt16(startDate[0]), Convert.ToInt16(startDate[1]));
                     pr.EndDate = new DateTime(Convert.ToInt16(endDate[2]), Convert.ToInt16(endDate[0]), Convert.ToInt16(endDate[1]));
                }
                _service.UpdateProject(pr);
                return RedirectToAction("Index");
            }
            catch
            {
                return RedirectToAction("Edit");
            }
        }

        //
        // GET: /Project/Delete/5
 
        public ActionResult DeleteProject(int id)
        {
            bool error = true;
            string link = string.Empty;

            try
            {
                _model.DeleteProject(id);

                error = false;
                link =  "/Project/";

                return Json(new { error = error, href = link  });
            }
            catch (Exception ex)
            {
                string html = "Could not delete Project! " + ex.Message;
                link =  "/Project/View/" + id;
                return Json(new { error = error, html = html , href = link});
            }
          
        }

        public ActionResult FollowProject(int projectId, string userCan)
        {
            int userId = _userModel.GetUserId(HttpContext.User.Identity.Name);
            bool following = false;
            string html = string.Empty;
            userCan =  userCan.Trim();
            switch (userCan)
            {
                case "Follow":
                     following = _model.FollowProject(projectId,userId);  
                     html = "Unfollow";
                     return Json(new { error = !following, html = html });

                case "Unfollow":
                     bool unfollow =   _model.UnFollowProject(projectId,userId);  
                     html = "Follow";
                     return Json(new { error = !unfollow, html = html });
                default:
                    break;
            }
            return Json(new { error = !following, html = html });
        }

        public JsonResult JoinProject(int roleid, int projectId)
        {
             var userId = _userModel.GetUserId(HttpContext.User.Identity.Name);
            var html = string.Empty;
            switch (roleid)
            {

                case 1:
                    _service.JoinProject(userId, projectId, UserRoleType.Volunteer);
                    break;
                case 2:
                    _service.JoinProject(userId, projectId, UserRoleType.Staff);
                    break;
                default:
                    break;
                    
            }
            html = "Congratulation! You have joined this project!";
            return Json(new {html});
        }
    }
}
